const jwt = require("jsonwebtoken");

const {
  register,
  getUserInfo,
  updateById,
} = require("../service/user.service");

const { JWT_SECRET } = require("../config/config.default");

class UserController {
  /**
   * 用户注册
   * @param {*} ctx
   * @param {*} next
   */
  async register(ctx, next) {
    // 获取数据
    const { user_name, password } = ctx.request.body;
    // 操作数据库
    try {
      const res = await register(user_name, password);
      ctx.body = {
        code: 0,
        message: "用户注册成功",
        data: {
          id: res.id,
          user_name: res.user_name,
        },
      };
    } catch (error) {
      console.log(error);
      ctx.body = {
        code: 1,
        message: "用户注册失败",
      };
    }
  }
  /**
   * 用户登录
   * @param {*} ctx
   * @param {*} next
   */
  async login(ctx, next) {
    const { user_name } = ctx.request.body;
    try {
      const { password, ...res } = await getUserInfo({ user_name });
      // ctx.body = {
      //   code: 0,
      //   message: "用户登录成功",
      //   data: {
      //     token: jwt.sign(res, JWT_SECRET, { expiresIn: "1d" }),
      //   },
      // };
      ctx.success(0, "用户登录成功", {
        token: jwt.sign(res, JWT_SECRET, { expiresIn: "1d" }),
      });
    } catch (error) {
      console.error("用户登录失败", error);
    }
  }
  /**
   * 修改密码
   * @param {*} ctx
   * @param {*} next
   */
  async changePassword(ctx, next) {
    const id = ctx.state.user.id;
    const password = ctx.request.body.password;
    try {
      if (await updateById({ id, password })) {
        ctx.body = {
          code: 0,
          message: "修改密码成功",
        };
      } else {
        ctx.body = {
          code: "10007",
          message: "修改密码失败",
        };
      }
    } catch (error) {
      console.log(error);
    }
  }
}

module.exports = new UserController();
